
var lineHeight = 0;
var endWords = "";
var isNum;


import * as Api from '../../utils/api.js'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeColors:'',
    modelFilterInput: '',
    brandFilterInput: '',
    seriesFilterInput: '',
    defauCarId: '',
    cascader: false,//是否启动无图标体验效果模式
    "hidden": true,
    tabrId: '1',
    brand: '品牌',
    series: '车系',
    automobile: '车型',
    isHaveCar: false,
    goodsList: [
      {
        id: 'hot',
        classifyName: '热销',
        goods: [1, 2, 3, 4, 5]
      }
    ],
    bsmList: [],
    bsmSeriesList: [],
    bsmAutomobileList: [],
    carIndexList: {
      "hot": {
        hide: false
      },
      "A": {
        hide: false
      },
      "B": {
        hide: false
      },
      "C": {
        hide: false
      },
      "D": {
        hide: false
      },
      "E": {
        hide: true
      },
      "F": {
        hide: false
      },
      "G": {
        hide: false
      },
      "H": {
        hide: false
      },
      "I": {
        hide: false
      },
      "J": {
        hide: false
      },
      "K": {
        hide: false
      },
      "L": {
        hide: false
      },
      "M": {
        hide: false
      },
      "N": {
        hide: false
      },
      "O": {
        hide: false
      },
      "P": {
        hide: true
      },
      "Q": {
        hide: false
      },
      "R": {
        hide: false
      },
      "S": {
        hide: false
      },
      "T": {
        hide: false
      },
      "W": {
        hide: false
      },
      "X": {
        hide: false
      },
      "Y": {
        hide: false
      },
      "Z": {
        hide: false
      }
    },
    classifySeleted: 0,//选中的年份上级节点的下标
    classifyContent: [],
    pageType: 'add',
    vinBrandId:'',
  },
  changeTabrId(e) {
    if ((e.currentTarget.dataset.id === '2' || e.currentTarget.dataset.id === '3') && e.currentTarget.dataset.id !== '1' && this.data.brand === '品牌') {
      wx.showModal({
        title: '提示',
        content: '请选择一款品牌',
        showCancel: false,
        confirmText: '知道了',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      })
      return
    }
    if (e.currentTarget.dataset.id === '3' && this.data.series === '车系') {
      wx.showModal({
        title: '提示',
        content: '请选择一款车系',
        showCancel: false,
        confirmText: '知道了',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      })
      return
    }
    console.log('44')
    console.log(this.data.bsmSeriesList.length)
    this.setData({
      tabrId: e.currentTarget.dataset.id
    })
    if (this.data.vinBrandId && !this.data.bsmSeriesList.length){
      console.log(55)
      this.setData({
        tabrId: '2'
      })
      this.getBsmList(this.data.vinBrandId)
      return
    }
    if (this.data.vinBrandId && !this.data.bsmList.length && this.data.tabrId == '1') {
      
      this.getBsmList()
    }

   
  },

  brandClear(){
    
    this.changeInputBrand({
      detail: {
        value: ''
      }
    })

  },
  seriesClear(){
    this.changeInputSeries({
      detail: {
        value: ''
      }
    })

  },
  modelClear(){
    this.changeInputModel({
      detail: {
        value: ''
      }
    })
  },
  //品牌搜索
  changeInputBrand(e) {

  
    this.data.bsmList.forEach((item, brandIndex) => {
      for (let opt in item) {
        let count = true
        item[opt].forEach((cat, catIndex, arr) => {
          if (cat.brandName) {
            cat.brandName.indexOf(e.detail.value) !== -1 ? count = false : ''
            Object.assign(cat, { hide: cat.brandName.indexOf(e.detail.value) === -1 })
          } else {
            //第N次给索引赋隐藏值
            // A:{ ... , { hide: true,count: count}}

            this.data.carIndexList[opt].hide = count
            arr[catIndex] = {
              hide: true,
              count: count
            }
          }
        })
        //第一次给索引赋隐藏值  
        // A:{ ... }
        if (item[opt][item[opt].length - 1].brandName) {
          this.data.carIndexList[opt].hide = count
          item[opt][item[opt].length] = {
            hide: true,
            count: count
          }
        }
        // A:{ ... , { hide: true,count: count}}
      }
    })




    this.setData({
      brandFilterInput: e.detail.value,
      bsmList: this.data.bsmList,
      carIndexList: this.data.carIndexList
    })

  },

  changeInputSeries(e) {


    this.data.bsmSeriesList.forEach((item, brandIndex) => {
      Object.assign(item, { hide: item.seriesName.indexOf(e.detail.value) === -1 })
    })

    this.setData({
      seriesFilterInput: e.detail.value,
      bsmSeriesList: this.data.bsmSeriesList
    })
  },







  changeInputModel(e) {


    // this.setData({
    //   classifyContent: this.data.bsmAutomobileList[this.data.classifySeleted],
    // })
    if (e.detail.value === '') {
      //当空字符时还原
      this.data.bsmAutomobileList.forEach((item, brandIndex) => {
        for (let opt in item) {
          let count = false

          item[opt].forEach((cat, catIndex, arr) => {
            if (cat.modelName) {
              this.setData({
                classifyContent: this.data.bsmAutomobileList[this.data.classifySeleted],
              })
              count = false
              Object.assign(cat, { hide: count })
            } else {
              arr[catIndex] = {
                hide: true,
                count: count
              }
            }
          })


        }
      })

    } else {
      let initSelect = true
      this.data.bsmAutomobileList.forEach((item, brandIndex) => {
        for (let opt in item) {
      
          let count = true

          item[opt].forEach((cat, catIndex, arr) => {
            if (cat.modelName) {

              if (cat.modelName.indexOf(e.detail.value) !== -1) {
                console.log(cat.modelName,'!=-1')

                //分组选择的时候  筛选   选中第一个结果的年份
                if (initSelect) {
                  this.setData({
                    classifySeleted: brandIndex              
                  })
                  initSelect = false
                }

                count = false
              }
              console.log(cat.modelName,cat.modelName.indexOf(e.detail.value) === -1)
              Object.assign(cat, { hide: cat.modelName.indexOf(e.detail.value) === -1 })



            } else {
              arr[catIndex] = {
                hide: true,
                count: count
              }
            }
          })

          if (item[opt][item[opt].length - 1].modelName) {
            item[opt][item[opt].length] = {
              hide: true,
              count: count
            }

          }

        }
      })

    }



    this.setData({
      modelFilterInput: e.detail.value,
      bsmAutomobileList: this.data.bsmAutomobileList,
      classifyContent: this.data.bsmAutomobileList[this.data.classifySeleted],
    })
  },
  removeByValue(arr, val) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == val) {
        arr.splice(i, 1);
        break;
      }
    }
  },
  //触发全部开始选择
  chStart: function () {
    console.log('开始')

    this.setData({
      trans: ".05",
      hidden: false
    })
  },
  //触发结束选择
  chEnd: function () {


    this.setData({
      hidden: true,
      scrollTopId: this.endWords
    })


  },
  //获取文字信息
  getWords: function (e) {
    var id = e.target.id;
    this.endWords = id;
    isNum = id;
    this.setData({
      showwords: this.endWords
    })
  },
  //设置文字信息
  setWords: function (e) {
    var id = e.target.id;
    this.setData({
      scrollTopId: id
    })
  },

  // 滑动选择城市
  chMove: function (e) {

    var y = e.touches[0].clientY;
    var offsettop = e.currentTarget.offsetTop;
    var height = 0;
    var that = this;
    ;
    var cityarr = ["热", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"]
    // 获取y轴最大值
    wx.getSystemInfo({
      success: function (res) {
        height = res.windowHeight - 10;
      }
    });

    //判断选择区域,只有在选择区才会生效
    if (y > offsettop && y < height) {
      // console.log((y-offsettop)/lineHeight)
      var num = parseInt((y - offsettop) / lineHeight);
      endWords = cityarr[num];
      // 这里 把endWords 绑定到this 上，是为了手指离开事件获取值
      that.endWords = endWords;


    };


    //去除重复，为了防止每次移动都赋值 ,这里限制值有变化后才会有赋值操作，
    //DOTO 这里暂时还有问题，还是比较卡，待优化
    if (isNum != num) {
      // console.log(isNum);
      isNum = num;
      that.setData({
        showwords: that.endWords
      })
    }

    that.setData({
      trans: "0",
      scrollTopId: that.endWords
    })




  },
  getGclinkList() {
    let self = this
    // 是否启用力洋接口
    let url = app.globalData.baseUrl1 + '/goods/front/gclinklist'
    let data = {
      carId: app.globalData.carId,
      userId: app.globalData.userId ? app.globalData.userId : '',
      merchantId: app.globalData.merchant.merchantId
    }
    //发起网络请求
    let callBack = (res) => {
      console.log(res)
      if (res == null) {
        console.log("网络请求错误！");
        return;
      }

      if (res.statusCode != 200) {
        console.log("请求数据错误");
        return;
      }
      if (res.statusCode === 200) {
        console.log(res.data.data.goodsDetailList)
        if (res.data.data.goodsDetailList && res.data.data.goodsDetailList.length > 0) {
          if (res.data.data.goodsDetailList.length == 1) {
            wx.navigateTo({
              url: '../product_datil/product_datil?id=' + res.data.data.goodsDetailList[0].goodsId + '&carId=' + app.globalData.carId 
            })
          }else{
            wx.navigateTo({
              url: '../../order_result/order_result'
            })
          }
        }


      }
    }
    Api.reqFormPost(url, data, callBack)
  },

  selectAutomobile(e) {
    app.globalData.carId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../../order_result/order_result'
    })
    return
  
    if (app.globalData.userId == null) {
      // 改为普通单品方式
       this.goPage(e.currentTarget.dataset.id)
      // wx.redirectTo({
      //   url: '../../core/login/login'
      // })
       return
    }
 


    let self = this
    let url = app.globalData.baseUrl1 + '/user/defaultcar';
    let data = {
      token: app.globalData.token ? app.globalData.token :'',
      userId: app.globalData.userId ? app.globalData.userId:'',
      carId: e.currentTarget.dataset.id
    }
    let callBack = (res) => {

      if (res == null) {

        console.log("网络请求错误！");
        return;
      }
      if (res.data.status != 200) {
        console.log("请求数据错误");
        return;
      }
      self.goPage(e.currentTarget.dataset.id)
    }
    Api.reqFormPost(url, data, callBack)


  },
  goPage(modelId) {
    let self = this
    let url = app.globalData.baseUrl + '/merchant/catlist'
    this.setData({
      subModelId: modelId
    })
    let data = {
      merchantId: app.globalData.merchant.merchantId,
      modelId: modelId
    }
    console.log(this.data.subModelId)

    //发起网络请求
    let callBack = (res) => {
      console.log(self.subModelId)
      if (res == null) {
        console.log("网络请求错误！");
        return;
      }
      if (res.statusCode != 200) {
        console.log("请求数据错误");
        return;
      }
      if (res.statusCode === 200) {
        let selfs = self
        console.log(selfs)
        // 当前只有一个分类且当前只有一个商品
        console.log(res.data.data.goodsCount[res.data.data.children[0].catId])
        console.log(res.data.data.children.length)
        if (res.data.data.children.length == 1 && res.data.data.goodsCount[res.data.data.children[0].catId] === 1) {
          // 请求获取商品id
          let goodsUrl = app.globalData.baseUrl1 + '/goods/front/list'
          let datas = {
            merchantId: app.globalData.merchant.merchantId,
            userId: app.globalData.userId ? app.globalData.userId : '',
            firstCatId: res.data.data.children[0].parentId,
            secCatIds: res.data.data.children[0].catId,//二级分类id
            carId: modelId
          }

          let callBacks = (result) => {
            let targetSelf = selfs
            console.log(targetSelf)
            if (result == null) {
              console.log("网络请求错误！");
              return;
            }
            if (result.statusCode != 200) {
              console.log("请求数据错误");
              return;
            }
            console.log(result.data.data.length)
            console.log(targetSelf.data.hasGoneAway)
            if (result.data.data.length > 0) {
              wx.navigateTo({
                url: '../product_datil/product_datil?id=' + result.data.data[0].goodsId + '&carId=' + targetSelf.data.subModelId,
                success: function (res) {
                  console.log(555)

                },
                fail: function (res) { },
                complete: function (res) { },
              })

            }
          }
          Api.reqFormPost(goodsUrl, datas, callBacks)
        } else {
          console.log(33)
          wx.redirectTo({
            url: '../../order_result/order_result'
          })
        }
        self.setData({
          categoryList: res.data.data.children,
          goodsCount: res.data.data.goodsCount
        })
      }
    }
    Api.reqFormPost(url, data, callBack)
  },
  // 选择品牌
  selectBrand(e) {
    this.setData({
      tabrId: '2',
      brand: e.currentTarget.dataset.name,
      series: '车系'
    })
    this.getBsmList(e.currentTarget.dataset.id)
  },
  // 选择车系
  selectSeries(e) {
    this.setData({
      tabrId: '3',
      series: e.currentTarget.dataset.name,
      classifySeleted: 0
    })
    this.getBsmList(e.currentTarget.dataset.brandid, e.currentTarget.dataset.id)
  },
  // 选择车型年份
  classifySelete(e) {
    console.log(e.currentTarget.dataset)
    this.setData({
      classifySeleted: e.currentTarget.dataset.activeindex,
      classifyContent: this.data.bsmAutomobileList[e.currentTarget.dataset.activeindex]
    })

  },

  // 获取数据
  getBsmList: function (...args) {

    wx.showLoading({
      mask: true,
      title: '加载中'
    })
    let self = this
    let url = app.globalData.baseUrl + '/bsm'
    let data = {

    }
    if (this.data.tabrId === '1') {
      data = {
        merchantId: app.globalData.merchant.merchantId,
        brandId: '',
        seriesId: '',
      }
    } else if (this.data.tabrId === '2') {

      data = {
        merchantId: app.globalData.merchant.merchantId,
        
        brandId: args[0],
        seriesId: '',
      }
    } else if (this.data.tabrId === '3') {

      data = {

        merchantId: app.globalData.merchant.merchantId,
        
        brandId: args[0],
        seriesId: args[1]
      }
    }


    //发起网络请求
    let callBack = (res) => {
      wx.hideLoading()
      if (res == null) {
        console.log("网络请求错误！");
        return;
      }

      if (res.statusCode != 200) {
        console.log("请求数据错误");
        return;
      }
      if (res.statusCode === 200) {
        // console.log(res)


        if (self.data.tabrId === '1') {

          self.setData({
            bsmList: res.data.data,
          })
          wx.setStorageSync('brandList', JSON.stringify(res.data.data))
        
          if (self.data.defauCarId) {
            self.getDefaultCarItem(self.data.defauCarId)
          }
        } else if (self.data.tabrId === '2') {
          self.setData({
            bsmSeriesList: res.data.data
          })
          if (self.data.defauCarId) {
            self.getDefaultCarItem(self.data.defauCarId)
          }

        } else {
          let bsmAutomobileList = []
          for (let i = 0; i < res.data.data.length; i++) {
            bsmAutomobileList.push(res.data.data[i])
          }
          if (bsmAutomobileList.length > 0) {
            self.setData({
              classifyContent: bsmAutomobileList[self.data.classifySeleted]
            })
          }
          self.setData({
            bsmAutomobileList: bsmAutomobileList
          })
          if (self.data.defauCarId) {
            self.getDefaultCarItem(self.data.defauCarId)
          }


        }



      }


    }
    Api.reqFormPost(url, data, callBack)
  },
  //达到默认已选择效果
  getDefaultCarItem(carId) {
    let self = this
    let url = app.globalData.baseUrl + '/bsm'
    let data = {
      merchantId: app.globalData.merchant.merchantId,
      modelId: carId
    }
    //发起网络请求
    let callBack = (res) => {
      if (res == null) {
        console.log("网络请求错误！");
        return;
      }

      if (res.statusCode != 200) {
        console.log("请求数据错误");
        return;
      }
      if (res.statusCode === 200) {
        console.log('默认选择车型', res.data.data)

        this.setData({
          brand: res.data.data.brandName,
          series: res.data.data.seriesName,
        })

        if (this.data.tabrId === '1') {
          self.selectBrand({
            currentTarget: {
              dataset: {
                name: res.data.data.brandName,
                id: res.data.data.brandId
              }
            }
          })
        } else if (this.data.tabrId === '2') {

          self.selectSeries({
            currentTarget: {
              dataset: {
                name: res.data.data.seriesName,
                id: res.data.data.seriesId,
                brandid: res.data.data.brandId
              }
            }
          })
        } else if (this.data.tabrId === '3') {
          self.setData({
            defauCarId: false
          })
          let opt = 0
          this.data.bsmAutomobileList.forEach((item, index) => {
            console.log(item[res.data.data.years])
            if (item[res.data.data.years]) {
              opt = index
            }
          });
          self.classifySelete({
            currentTarget: {
              dataset: {
                activeindex: opt
              }
            }
          })

        }



      }



    }
    Api.reqFormPost(url, data, callBack)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let _this = this
    if (app.globalData.merchant === null) {
      app.doLogin(this.onLoad, this.onShow, options);
      return
    }
    // 如果是点选的
    if (options.brandId && options.seriesId) {
      this.setData({
        tabrId: '3',
        series: options.seriesName ,
        brand: options.brandName,
        classifySeleted: 0,
        vinBrandId: options.brandId,
        themeColors: app.globalData.merchant.themeColors
      })
      this.getBsmList(options.brandId, options.seriesId)
      return
    }
    console.log('加载bsm')
    // wx.getStorage({
    //   key: 'brandList',
    //   success: function (res) {
    //     console.log(res.data)
    //     if(res.data.length>0){
    //       console.log(_this)
    //       // _this.setData({
    //       //   bsmList: res.data
    //       // })
    //     }
    //   }
    // })
    if (wx.getStorageSync('brandList') && JSON.parse(wx.getStorageSync('brandList')).length>0){
      let data = JSON.parse(wx.getStorageSync('brandList'))
      console.log(data[0])
      console.log(data)
      this.setData({
        bsmList: [data[0]]
      })
    }
   // brandList
    let self = this
     self.getBsmList()
    if (options.carId) {
      self.setData({
        defauCarId: options.carId
      })
    } else {
      self.setData({
        defauCarId: false
      })
    }
    self.setData({
      cascader: app.globalData.merchant.cascader,
     themeColors : app.globalData.merchant.themeColors
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 生命周期函数--监听页面初次渲染完成

    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        lineHeight = (res.windowHeight - 100) / 26;
        console.log(res.windowHeight - 100)
        that.setData({

          winHeight: res.windowHeight -40,
          lineHeight: lineHeight
        })

      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.merchant === null) {
      return
    } 
    if (app.globalData.merchant.mustLogin && app.globalData.userId === null) {
      wx.navigateTo({
        url: '/pages/core/login/login',
        success() {
          wx.showToast({
            title: '请先登陆',
            icon: 'loading',
            duration: 1000
          })
        }
      })
      return
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})